package com.czxy.advert.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.czxy.advert.config.OssProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author 桐叔
 * @email liangtong@itcast.cn
 */
@Component
public class OssUtils {
    @Resource
    private OssProperties ossProperties;
    public String upload(MultipartFile file) {
        if(file == null) {
            throw new RuntimeException("上传文件为空");
        }

        try {

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getKeyId(), ossProperties.getKeySecret());

            String path = ossProperties.getDirName() + "/" + System.currentTimeMillis() + ".png";

            // 数据流
            InputStream inputStream = file.getInputStream();
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(ossProperties.getBucketName(), path, inputStream);


            // 关闭OSSClient。
            ossClient.shutdown();

            String url = "https://"+ossProperties.getBucketName()+"."+ossProperties.getEndpoint()+"/" + path;
            return url;
        } catch (IOException e) {
            throw new RuntimeException("文件上传有误");
        }

    }
}